import { useAuth } from '@/hooks/business/auth';

/** 按钮权限管理工具类 */
export class ButtonPermissionManager {
  private static instance: ButtonPermissionManager;
  private authHook: ReturnType<typeof useAuth>;

  private constructor() {
    this.authHook = useAuth();
  }

  public static getInstance(): ButtonPermissionManager {
    if (!ButtonPermissionManager.instance) {
      ButtonPermissionManager.instance = new ButtonPermissionManager();
    }
    return ButtonPermissionManager.instance;
  }

  /**
   * 检查是否有按钮权限（异步版本）
   *
   * @param codes 按钮权限代码，可以是单个字符串或字符串数组
   * @returns Promise<boolean>
   */
  async hasPermission(codes: string | string[]): Promise<boolean> {
    return await this.authHook.hasAuth(codes);
  }

  /**
   * 检查是否有按钮权限（同步版本）
   *
   * @param codes 按钮权限代码，可以是单个字符串或字符串数组
   * @returns boolean
   */
  hasPermissionSync(codes: string | string[]): boolean {
    return this.authHook.hasAuthSync(codes);
  }

  /**
   * 获取用户所有按钮权限
   *
   * @returns Promise<string[]>
   */
  async getUserPermissions(): Promise<string[]> {
    return await this.authHook.getUserButtonPermissions();
  }

  /** 清除按钮权限缓存 */
  clearCache(): void {
    this.authHook.clearButtonPermissionCache();
  }
}

/**
 * 创建按钮权限检查函数
 *
 * @returns 按钮权限检查函数
 */
export function createButtonPermissionChecker() {
  const manager = ButtonPermissionManager.getInstance();

  return {
    hasPermission: manager.hasPermission.bind(manager),
    hasPermissionSync: manager.hasPermissionSync.bind(manager),
    getUserPermissions: manager.getUserPermissions.bind(manager),
    clearCache: manager.clearCache.bind(manager)
  };
}

/**
 * 按钮权限指令的工厂函数
 *
 * @param codes 按钮权限代码
 * @returns 权限检查函数
 */
export function createButtonPermissionDirective(codes: string | string[]) {
  const manager = ButtonPermissionManager.getInstance();
  return () => manager.hasPermissionSync(codes);
}

/** 按钮权限组合式函数 */
export function useButtonPermission() {
  const manager = ButtonPermissionManager.getInstance();

  return {
    hasPermission: manager.hasPermission.bind(manager),
    hasPermissionSync: manager.hasPermissionSync.bind(manager),
    getUserPermissions: manager.getUserPermissions.bind(manager),
    clearCache: manager.clearCache.bind(manager)
  };
}
